#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
//全局变量

int high,width;//画面尺寸
int ball_x,ball_y;//小球位置
int ball_vx,ball_vy;//小球的速度
int position_x,position_y;//挡板中心坐标
int ridus;//挡板半径
int score;//游戏得分
int ball_number;
int left,right;
int block_x,block_y;//砖块位置

void gotoxy(int x,int y)//光标移动到(x,y)位置
{
    HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X=x;
    pos.Y=y;
    SetConsoleCursorPosition(handle,pos);
}

void HideCursor()
{
    CONSOLE_CURSOR_INFO cursor_info = {1, 0};
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

void startup()//数据初始化
{
   high =13;
   width =20;
   ball_x=0;
   ball_y=width/2;
   ball_vx=1;
   ball_vy=1;
   ridus=5;

   position_x=high;
   position_y=width/2;

   left=position_y-ridus;
   right=position_y+ridus;

   block_x=0;
   block_y=width/2;

   ball_number=0;

   score=0;

   HideCursor();//隐藏光标

}

void show()  //显示画面
{
    gotoxy(0,0);//光标移动到原点位置，以下重画清屏
    int i,j;

    for(i=0;i<=high+1;i++)
    {
        for(j=0;j<=width;j++)
        {
            if((i==ball_x)&&(j==ball_y))
                printf("0");//输出小球
            else if(j==width)
                printf("|");//输出右边框|
            else if((j==block_y)&&(i==block_x))
                printf("B");//输出砖块
            else if(i==high+1)
                printf("-");//输出下边框
            else if((i==high)&&(j>=left)&&(j<=right))
                printf("*");//输出挡板
            else
                printf(" ");//输出空格
        }
        printf("\n");
    }
    printf("反弹小球数:%d\n得分:%d\n",ball_number,score);
}
void updateWithoutInput()//与输入无关的更新
{
    if(ball_x==high-1)
    {
        if((ball_y>=left)&&(ball_y<=right))//被挡板挡住
        {
            ball_number++;
            printf("\a");
        }
        else
        {
            printf("Game Over\n");
            system("pause");
            exit(0);
        }
    }
    ball_x=ball_x+ball_vx;
    ball_y=ball_y+ball_vy;
    if((ball_x==0)||(ball_x==high-1))
        ball_vx=-ball_vx;
    if((ball_y==0)||(ball_y==width-1))
        ball_vy=-ball_vy;
    if((ball_x==block_x)&&(ball_x==block_y))
        score++;
    Sleep(50);
}
void updateWithInput()//与输入有关的更新
{
    char input;

    if(kbhit())//当按键时执行
    {
        input = getch();

        if(input=='a'){
            position_y--;
            left=position_y-ridus;
            right=position_y+ridus;
            }
        if(input=='d'){
            position_y++;
            left=position_y-ridus;
            right=position_y+ridus;
            }

    }
}


int main()
{
    startup();//数据初始化
    while(1) //游戏循环执行
    {
        show();  //显示画面
        updateWithoutInput();//与输入无关
        updateWithInput();//与输入有关
    }


    return 0;
}